package main.java.DMDE.persistence;

import java.util.UUID;

import main.java.DMDE.model.Entity;
import main.java.DMDE.model.Method;
import main.java.common.IXmlManager;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public abstract class EntityXmlManager implements IXmlManager<Entity> {

	protected MethodXmlManager methodManager = new MethodXmlManager();
	
	public Element getElementFromItem(Entity entity, Document document) {
		Element entityElement = document.createElement(getTag());
		fillElement(entityElement, entity, document);
		return entityElement;
	}

	public Entity getItemFromXmlElement(Element entityElement) throws Exception {
		Entity entity = getNewInstance();
		fillEntity(entity, entityElement);
		return entity;
	}

	protected void fillElement(Element entityElement, Entity entity, Document document) {
		entityElement.setAttribute("name", entity.getName());
		entityElement.setAttribute("id", entity.getId().toString());
		Element methods = document.createElement("methods");
		for (Method method : entity.getMethods()) {
			methods.appendChild(methodManager
					.getElementFromItem(method, document));
		}
		entityElement.appendChild(methods);
	}

	protected void fillEntity(Entity entity, Element entityElement) throws Exception {
		String name = entityElement.getAttribute("name");
		UUID id = UUID.fromString(entityElement.getAttribute("id"));
		NodeList methods = entityElement.getElementsByTagName("methods");
		NodeList methodsElem = methods.item(0) != null ?  methods.item(0).getChildNodes() : null;
		if (methodsElem != null) for (int i = 0; i < methodsElem.getLength(); i++) {
			Node node = methodsElem.item(i);
			if (node == null || !(node instanceof Element))
				continue;
			entity.addMethod((methodManager.getItemFromXmlElement((Element) node)));
		}
		entity.setName(name);
		entity.setId(id);
	}

	protected abstract String getTag();
	
	protected abstract Entity getNewInstance();
}
